import {getUser, getUserToken} from "@stores/localStorage.ts";
import {isNull} from "@utils/stringUtil.ts";
import {userJurisdictionLevel} from "@constants/userJurisdiction.js";

export function appInit(operation: () => void) {
    const url = window.location.pathname
    const result = canJump(url)
    if (result.fallback) {
        operation()
    } else {
        alert(result.msg)
        window.location.href = '/src/page/home/index.html'
    }
}

export function canJump(rawUrl: string): { fallback: boolean; msg: string } {
    const url = normalizeUrl(rawUrl)
    const userToken = getUserToken()
    const isLogin = !isNull(userToken) && getUser().hasUserMsg()
    const isResourcesAdmin = getUser().jurisdiction >= userJurisdictionLevel.RESOURCES_ADMIN_JURISDICTION.level
    if (isLogin && guestOnlyPages.some(path => url.includes(bestUrl + path))) {
        return {fallback: false, msg: '您已经登录了，请勿重复登录/注册'}
    }

    if (!isLogin && authOnlyPages.some(path => url.includes(bestUrl + path))) {
        return {fallback: false, msg: '您尚未登录，请先登录'}
    }

    if (!isResourcesAdmin && resourcesAdminOnlyPages.some(path => url.includes(bestUrl + path))) {
        return {fallback: false, msg: '您的权限不足,无法访问该页面'}
    }

    return {fallback: true, msg: ''}
}

export function jump(url: string) {
    const canJump1 = canJump(url);
    if (canJump1.fallback)
        window.location.href = url.startsWith('/') ? url : '/' + url
    else {
        alert(canJump1.msg)
    }

}

export function jumpInNewTab(url: string) {
    const result = canJump(url)
    if (result.fallback) {
        const fullUrl = url.startsWith('/') ? url : '/' + url
        window.open(fullUrl, '_blank')  // 打开新窗口
    } else {
        alert(result.msg)
    }
}

function normalizeUrl(url: string): string {
    return url.split('?')[0].split('#')[0].replace(/\.html$/, '').toLowerCase()
}

const bestUrl = '/src/page'
const guestOnlyPages = ['/login', '/register']  // 已登录用户不能访问
const authOnlyPages = ['/users']                 // 未登录用户不能访问
const resourcesAdminOnlyPages = ['/resourceManagement']                 // 未登录用户不能访问
